from enum import IntEnum
from peewee import *
from typing import *

class ItemState(IntEnum):  
    Temp=0  
    Collecting=1
    Collected=2
    Downloading=3
    Downloaded=4

db=SqliteDatabase('books.sqlite')
db.connect(reuse_if_open=True)

class ItemBase(Model):

    class Meta:
        database=db
        

class BookItem(ItemBase):
    # def __init__(self,title,chapter_count,chapters,url) -> None:
    #    self.url=url
    #    self.title=title
    #    self.chapters=chapters
    #    self.chapter_count=chapter_count
    title=CharField()
    chapter_count=IntegerField()
    url=TextField(unique=True)
    cover_url=TextField(null=True)
    state=SmallIntegerField(default=ItemState.Collecting)

    @property
    def progress(self):
        if self.state<=ItemState.Collecting:
            return -1
        elif self.state==ItemState.Collected:
            return 0
        progress=0
        for chapter in self.chapters:
            if chapter.state==ItemState.Downloaded:
                progress+=1
            elif chapter.state<ItemState.Downloading:
                continue
            else:
                down=PageItem.select().where(PageItem.chapter==self,PageItem.state==ItemState.Downloaded)
                progress+=down/chapter.page_count
        return progress/self.chapter_count
    
    @property
    def page_count(self):
        sum_toal=fn.SUM(ChapterItem.page_count).alias('total')
        query=ChapterItem.select(sum_toal).group_by(ChapterItem.book).where(ChapterItem.book==self)
        return list(query)[0].total


class ChapterItem(ItemBase):
    title=CharField()
    order=IntegerField()
    page_count=IntegerField()
    url=TextField(unique=True)
    state=SmallIntegerField(default=ItemState.Collecting)
    book=ForeignKeyField(BookItem,backref='chapters')

class PageItem(ItemBase):
    # def __init__(self,order,url) -> None:
    #     self.order=order
    #     self.url=url
    order=IntegerField()
    url=TextField(unique=True)
    state=SmallIntegerField(default=ItemState.Downloading)
    chapter=ForeignKeyField(ChapterItem,backref='pages')

def rebuild_db():
    # if os.path.exists('books.sqlite'):
    #     os.remove('books.sqlite')
    models=[BookItem,ChapterItem,PageItem]
    db.drop_tables(models)
    db.create_tables(models)

if __name__ == '__main__':
    pass